<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Request;

/**
 * 简单流式输出测试接口
 */
class SimpleStream extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 简单流式文本输出
     */
    public function chat(Request $request)
    {
        try {
            $question = trim($request->param('question', '你好世界'));
            
            // 设置流式响应头
            header('Content-Type: text/event-stream; charset=utf-8');
            header('Cache-Control: no-cache, no-store, must-revalidate');
            header('Pragma: no-cache');
            header('Expires: 0');
            header('Connection: keep-alive');
            header('Access-Control-Allow-Origin: *');
            header('X-Accel-Buffering: no');
            
            // 清除所有输出缓冲区
            while (ob_get_level() > 0) {
                ob_end_clean();
            }
            
            // 禁用PHP输出缓冲
            ini_set('output_buffering', 'off');
            ini_set('zlib.output_compression', 'off');
            ini_set('implicit_flush', '1');
            
            // 启用自动刷新
            ob_implicit_flush(true);
            
            // 设置无限制执行时间
            set_time_limit(0);
            
            echo "retry: 1000\n\n";
            flush();
            
            // 发送开始事件
            echo "event: start\n";
            echo "data: " . json_encode(['content' => '开始生成回答...'], JSON_UNESCAPED_UNICODE) . "\n\n";
            flush();
            
            // 模拟AI生成过程
            $responses = [
                "你好！",
                "很高兴",
                "与你",
                "交流。",
                "有什么",
                "我可以",
                "帮助",
                "你的吗？"
            ];
            
            foreach ($responses as $index => $content) {
                echo "event: content\n";
                echo "data: " . json_encode(['content' => $content], JSON_UNESCAPED_UNICODE) . "\n\n";
                flush();
                
                // 模拟处理延迟
                usleep(300000); // 300ms
            }
            
            // 发送处理完成事件
            echo "event: processed\n";
            echo "data: " . json_encode(['content' => implode('', $responses)], JSON_UNESCAPED_UNICODE) . "\n\n";
            flush();
            
            // 发送统计信息
            $stats = [
                'total_length' => mb_strlen(implode('', $responses), 'UTF-8'),
                'word_count' => count($responses),
                'processing_time' => time()
            ];
            
            echo "event: stats\n";
            echo "data: " . json_encode($stats, JSON_UNESCAPED_UNICODE) . "\n\n";
            flush();
            
            // 发送结束事件
            echo "event: end\n";
            echo "data: " . json_encode(['content' => '对话结束'], JSON_UNESCAPED_UNICODE) . "\n\n";
            flush();
            
        } catch (\Exception $e) {
            error_log('简单流式聊天错误: ' . $e->getMessage());
            
            // 设置流式响应头
            header('Content-Type: text/event-stream; charset=utf-8');
            
            // 清除所有输出缓冲区
            while (ob_get_level() > 0) {
                ob_end_clean();
            }
            
            echo "event: error\n";
            echo "data: " . json_encode(['content' => '系统错误: ' . $e->getMessage()], JSON_UNESCAPED_UNICODE) . "\n\n";
            echo "event: end\n";
            echo "data: " . json_encode(['content' => '连接结束'], JSON_UNESCAPED_UNICODE) . "\n\n";
            flush();
        }
        
        exit;
    }
}